package classLoader;

import java.io.IOException;
import java.io.InputStream;

/**
 * 类加载器与instanceof关键字演示
 * 1.根类加载器（root classloader）加载 java.lang and so on
 * 2.扩展类加载器（extension classloader）加载 javax开头的类库
 * 3.应用程序类加载器（application classloader）加载程序员自己写的业务代码
 * @Author Adam
 */
public class ClassLoaderTest {
    public static void main(String[] args) throws Exception{

        //自定义一个类加载器
         ClassLoader myLoader = new ClassLoader(){
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                try{
                    String fileName = name.substring(name.lastIndexOf(".")+1)+".class";
                    InputStream is =getClass().getResourceAsStream(fileName);
                    if (is==null){
                        return super.loadClass(name);
                    }
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    return defineClass(name,b,0,b.length);
                }catch (IOException e){
                    throw new ClassNotFoundException(name);
                }
            }
        };

         //自定义一个classloader，然后用自定义的classloader加载类文件，再实例化对象
        Object obj = myLoader.loadClass("classLoader.ClassLoaderTest").newInstance();
        System.out.println(obj.getClass());
        //类加载器不一样
        System.out.println(obj instanceof classLoader.ClassLoaderTest);
    }
}
